package linked

type Node struct {
	E        interface{}
	PreNode  *Node
	NextNode *Node
}
type Linked struct {
	FirstNode *Node
	LastNode  *Node
	Size      int
}

func NewLinked() *Linked {
	return &Linked{Size: -1}
}

func (receiver *Linked) Add(ele interface{}) {
	node := &Node{}
	node.E = ele
	if receiver.Size == -1 {
		receiver.FirstNode = node
		receiver.LastNode = node
	} else {
		node.PreNode = receiver.LastNode
		receiver.LastNode.NextNode = node
		receiver.LastNode = node
	}
	receiver.Size = receiver.Size + 1
}

// Remove 移除并返回
func (receiver *Linked) Remove(index int) interface{} {
	node := receiver.GetNode(index)
	if node == nil {
		return nil
	}
	preNode := node.PreNode
	nextNode := node.NextNode
	if preNode == nil { //上一个为空,代表删除的是第一个节点
		nextNode.PreNode = nil
		receiver.FirstNode = nextNode
	} else if nextNode == nil { //下一个为空,代表删除的是最后一个节点
		receiver.LastNode = preNode
		preNode.NextNode = nil
	} else {
		preNode.NextNode = nextNode //删除中间节点
	}
	receiver.Size = receiver.Size - 1
	return node.E
}

func (receiver *Linked) Get(index int) interface{} {
	if index > receiver.Size {
		return nil
	}
	if index == receiver.Size {
		return receiver.LastNode.E
	}
	node := receiver.FirstNode
	for i := 0; i < index; i++ {
		node = node.NextNode
	}
	return node.E
}
func (receiver *Linked) GetNode(index int) *Node {
	if index > receiver.Size {
		return nil
	}
	if index == receiver.Size {
		return receiver.LastNode
	}
	node := receiver.FirstNode
	for i := 0; i < index; i++ {
		node = node.NextNode
	}
	return node
}
